//! # Git配置存储
//!
//! 基于Git仓库的配置存储实现，支持版本控制、分支管理、
//! 标签管理等Git原生功能，是分布式配置中心的核心存储后端。
//!
//! ## 核心功能
//!
//! * **Git仓库集成** - 支持本地和远程Git仓库
//! * **分支管理** - 不同环境使用不同分支
//! * **标签管理** - 配置版本标签管理
//! * **自动同步** - 自动从远程仓库拉取更新
//! * **冲突解决** - 配置文件冲突自动解决
//! * **操作原子性** - 保证Git操作的原子性
//!
//! ## 目录结构
//!
//! ```
//! config-repo/
//! ├── application.yaml          # 默认配置
//! ├── application-dev.yaml      # 开发环境配置
//! ├── application-test.yaml     # 测试环境配置
//! ├── application-prod.yaml     # 生产环境配置
//! ├── user-service.yaml         # 特定应用配置
//! ├── user-service-dev.yaml     # 应用开发环境配置
//! └── shared/                   # 共享配置目录
//!     ├── database.yaml         # 数据库配置
//!     └── cache.yaml            # 缓存配置
//! ```

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use async_trait::async_trait;
use git2::{Repository, Signature, ObjectType, Oid};
use serde_json::Value;
use tokio::fs;
use tokio::sync::Mutex;

use crate::RustCloudConfig;
use crate::core::{
    ConfigurationStorage, ConfigEnvironment, ConfigurationResult, ConfigurationData,
    PropertySource,
};
use super::{
    ConfigChangeRecord, ConfigurationServerConfig, ConfigurationServerError, ServerResult,
};

/// Git存储后端
pub struct GitStorage {
    /// Git仓库路径
    repo_path: PathBuf,
    /// Git仓库实例
    repository: Mutex<Option<Repository>>,
    /// 远程仓库URL
    remote_url: Option<String>,
    /// Git用户名
    username: Option<String>,
    /// Git密码或Token
    password: Option<String>,
    /// 默认分支
    default_branch: String,
    /// 配置文件扩展名
    config_extension: String,
}

impl GitStorage {
    /// 创建新的Git存储
    pub fn new(config: &ConfigurationServerConfig) -> ServerResult<Self> {
        let repo_path = config.git_repo_path.clone()
            .unwrap_or_else(|| PathBuf::from("./config-repo"));
        
        let storage = Self {
            repo_path,
            repository: Mutex::new(None),
            remote_url: config.git_repo_url.clone(),
            username: config.git_username.clone(),
            password: config.git_password.clone(),
            default_branch: "main".to_string(),
            config_extension: "yaml".to_string(),
        };
        
        Ok(storage)
    }
    
    /// 初始化Git仓库
    pub async fn initialize(&self) -> ServerResult<()> {
        let mut repo_guard = self.repository.lock().await;
        
        // 检查仓库是否已存在
        if self.repo_path.exists() {
            // 打开现有仓库
            match Repository::open(&self.repo_path) {
                Ok(repo) => {
                    tracing::info!("📁 打开现有Git仓库: {:?}", self.repo_path);
                    *repo_guard = Some(repo);
                }
                Err(e) => {
                    return Err(ConfigurationServerError::StorageError(
                        format!("打开Git仓库失败: {}", e)
                    ));
                }
            }
        } else {
            // 创建新仓库或克隆远程仓库
            if let Some(remote_url) = &self.remote_url {
                // 克隆远程仓库
                tracing::info!("📥 克隆远程Git仓库: {} -> {:?}", remote_url, self.repo_path);
                
                let mut builder = git2::build::RepoBuilder::new();
                if let (Some(username), Some(password)) = (&self.username, &self.password) {
                    let mut callbacks = git2::RemoteCallbacks::new();
                    callbacks.credentials(|_url, username_from_url, _allowed_types| {
                        git2::Cred::userpass_plaintext(
                            username_from_url.unwrap_or(username),
                            password,
                        )
                    });
                    
                    let mut fetch_options = git2::FetchOptions::new();
                    fetch_options.remote_callbacks(callbacks);
                    builder.fetch_options(fetch_options);
                }
                
                match builder.clone(remote_url, &self.repo_path) {
                    Ok(repo) => {
                        *repo_guard = Some(repo);
                    }
                    Err(e) => {
                        return Err(ConfigurationServerError::StorageError(
                            format!("克隆Git仓库失败: {}", e)
                        ));
                    }
                }
            } else {
                // 创建本地仓库
                tracing::info!("📝 创建本地Git仓库: {:?}", self.repo_path);
                
                fs::create_dir_all(&self.repo_path).await?;
                
                match Repository::init(&self.repo_path) {
                    Ok(repo) => {
                        *repo_guard = Some(repo);
                        
                        // 创建初始提交
                        self.create_initial_commit().await?;
                    }
                    Err(e) => {
                        return Err(ConfigurationServerError::StorageError(
                            format!("初始化Git仓库失败: {}", e)
                        ));
                    }
                }
            }
        }
        
        // 拉取最新更新
        if self.remote_url.is_some() {
            if let Err(e) = self.pull_updates().await {
                tracing::warn!("⚠️ 拉取Git更新失败: {}", e);
            }
        }
        
        Ok(())
    }
    
    /// 创建初始提交
    async fn create_initial_commit(&self) -> ServerResult<()> {
        let repo_guard = self.repository.lock().await;
        if let Some(repo) = repo_guard.as_ref() {
            // 创建默认配置文件
            let config_content = r#"# 默认配置文件
application:
  name: "default-app"
  version: "1.0.0"
  port: 8080

registry:
  registry_type: "nacos"
  server_addr: "127.0.0.1:8848"
"#;
            
            let config_path = self.repo_path.join("application.yaml");
            fs::write(&config_path, config_content).await?;
            
            // 添加文件到索引
            let mut index = repo.index()
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            index.add_path(Path::new("application.yaml"))
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            let tree_oid = index.write_tree()
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            let tree = repo.find_tree(tree_oid)
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            // 创建签名
            let signature = Signature::now("Config Server", "config@rustcloud.com")
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            // 创建初始提交
            repo.commit(
                Some("HEAD"),
                &signature,
                &signature,
                "Initial commit",
                &tree,
                &[],
            ).map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            tracing::info!("✅ 创建初始Git提交");
        }
        
        Ok(())
    }
    
    /// 拉取远程更新
    async fn pull_updates(&self) -> Result<()> {
        let repo_guard = self.repository.lock().await;
        if let Some(repo) = repo_guard.as_ref() {
            // 获取远程引用
            let mut remote = repo.find_remote("origin")
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            // 设置认证回调
            let mut callbacks = git2::RemoteCallbacks::new();
            if let (Some(username), Some(password)) = (&self.username, &self.password) {
                callbacks.credentials(|_url, username_from_url, _allowed_types| {
                    git2::Cred::userpass_plaintext(
                        username_from_url.unwrap_or(username),
                        password,
                    )
                });
            }
            
            // 拉取更新
            remote.fetch(&[] as &[&str], Some(&mut git2::FetchOptions::new()), None)
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            // 合并更新
            let fetch_head = repo.fetchhead_foreach(|ref_name, remote_url, oid, is_merge| {
                if is_merge {
                    tracing::debug!("📥 合并更新: {} -> {}", ref_name, oid);
                }
                true
            }).map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            tracing::debug!("🔄 Git更新已拉取");
        }
        
        Ok(())
    }
    
    /// 推送更新到远程
    async fn push_updates(&self, message: &str) -> Result<()> {
        let repo_guard = self.repository.lock().await;
        if let Some(repo) = repo_guard.as_ref() {
            if self.remote_url.is_some() {
                let mut remote = repo.find_remote("origin")
                    .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
                
                // 设置认证回调
                let mut callbacks = git2::RemoteCallbacks::new();
                if let (Some(username), Some(password)) = (&self.username, &self.password) {
                    callbacks.credentials(|_url, username_from_url, _allowed_types| {
                        git2::Cred::userpass_plaintext(
                            username_from_url.unwrap_or(username),
                            password,
                        )
                    });
                }
                
                // 推送到远程
                let mut push_options = git2::PushOptions::new();
                push_options.remote_callbacks(callbacks);
                
                remote.push(
                    &[&format!("refs/heads/{}", self.default_branch)],
                    Some(&mut push_options),
                ).map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
                
                tracing::info!("📤 Git更新已推送: {}", message);
            }
        }
        
        Ok(())
    }
    
    /// 生成配置文件路径
    fn get_config_file_path(&self, environment: &ConfigEnvironment) -> PathBuf {
        let filename = if environment.application == "application" {
            if environment.profile == "default" {
                format!("application.{}", self.config_extension)
            } else {
                format!("application-{}.{}", environment.profile, self.config_extension)
            }
        } else {
            if environment.profile == "default" {
                format!("{}.{}", environment.application, self.config_extension)
            } else {
                format!("{}-{}.{}", environment.application, environment.profile, self.config_extension)
            }
        };
        
        self.repo_path.join(filename)
    }
    
    /// 提交配置变更
    async fn commit_changes(&self, message: &str, user: &str) -> Result<String> {
        let repo_guard = self.repository.lock().await;
        if let Some(repo) = repo_guard.as_ref() {
            // 添加所有变更到索引
            let mut index = repo.index()
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            index.add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            let tree_oid = index.write_tree()
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            let tree = repo.find_tree(tree_oid)
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            // 获取HEAD提交
            let head_ref = repo.head()
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            let head_commit = head_ref.peel_to_commit()
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            // 创建签名
            let signature = Signature::now(user, &format!("{}@rustcloud.com", user))
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            // 创建提交
            let commit_oid = repo.commit(
                Some("HEAD"),
                &signature,
                &signature,
                message,
                &tree,
                &[&head_commit],
            ).map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            let commit_id = commit_oid.to_string();
            tracing::info!("💾 创建Git提交: {} - {}", commit_id, message);
            
            Ok(commit_id)
        } else {
            Err(ConfigurationServerError::GitError("Git仓库未初始化".to_string()))
        }
    }
}

#[async_trait]
impl ConfigurationStorage for GitStorage {
    async fn load(&self, environment: &ConfigEnvironment) -> ConfigurationResult<ConfigurationData> {
        // 确保仓库已初始化
        if self.repository.lock().await.is_none() {
            self.initialize().await.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
        }
        
        let config_path = self.get_config_file_path(environment);
        
        if !config_path.exists() {
            return Err(Box::new(ConfigurationServerError::ConfigNotFound {
                application: environment.application.clone(),
                profile: environment.profile.clone(),
                label: environment.label.clone(),
            }) as Box<dyn std::error::Error + Send + Sync>);
        }
        
        // 读取配置文件
        let config_content = fs::read_to_string(&config_path).await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
        
        // 解析配置
        let config: RustCloudConfig = match self.config_extension.as_str() {
            "yaml" | "yml" => serde_yaml::from_str(&config_content)
                .map_err(|e| Box::new(ConfigurationServerError::SerializationError {
                    source: serde_json::Error::io(std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))
                }) as Box<dyn std::error::Error + Send + Sync>)?,
            "json" => serde_json::from_str(&config_content)
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?,
            "toml" => toml::from_str(&config_content)
                .map_err(|e| Box::new(ConfigurationServerError::SerializationError {
                    source: serde_json::Error::io(std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))
                }) as Box<dyn std::error::Error + Send + Sync>)?,
            _ => return Err(Box::new(ConfigurationServerError::StorageError(
                format!("不支持的配置文件格式: {}", self.config_extension)
            )) as Box<dyn std::error::Error + Send + Sync>),
        };
        
        // 转换为JSON Value
        let config_value = serde_json::to_value(&config)?;
        let mut properties = HashMap::new();
        
        if let Value::Object(map) = config_value {
            for (key, value) in map {
                properties.insert(key, value);
            }
        }
        
        // 获取Git版本信息
        let version = {
            let repo_guard = self.repository.lock().await;
            if let Some(repo) = repo_guard.as_ref() {
                repo.head()
                    .and_then(|head| head.peel_to_commit())
                    .map(|commit| commit.id().to_string())
                    .unwrap_or_else(|_| "unknown".to_string())
            } else {
                "unknown".to_string()
            }
        };
        
        let response = ConfigurationData {
            environment: environment.clone(),
            config: config.clone(),
            version,
            last_modified: SystemTime::now(),
            source: config_path.to_string_lossy().to_string(),
            properties: properties,
        };
        
        Ok(response)
    }
    
    async fn save(
        &self,
        environment: &ConfigEnvironment,
        config: &RustCloudConfig,
        user: &str,
    ) -> ConfigurationResult<String> {
        // 确保仓库已初始化
        if self.repository.lock().await.is_none() {
            self.initialize().await?;
        }
        
        let config_path = self.get_config_file_path(environment);
        
        // 确保目录存在
        if let Some(parent) = config_path.parent() {
            fs::create_dir_all(parent).await?;
        }
        
        // 序列化配置
        let config_content = match self.config_extension.as_str() {
            "yaml" | "yml" => serde_yaml::to_string(config)
                .map_err(|e| Box::new(ConfigurationServerError::SerializationError {
                    source: serde_json::Error::io(std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))
                }) as Box<dyn std::error::Error + Send + Sync>)?,
            "json" => serde_json::to_string_pretty(config)
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?,
            "toml" => toml::to_string(config)
                .map_err(|e| Box::new(ConfigurationServerError::SerializationError {
                    source: serde_json::Error::io(std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))
                }) as Box<dyn std::error::Error + Send + Sync>)?,
            _ => return Err(Box::new(ConfigurationServerError::StorageError(
                format!("不支持的配置文件格式: {}", self.config_extension)
            )) as Box<dyn std::error::Error + Send + Sync>),
        };
        
        // 写入配置文件
        fs::write(&config_path, config_content).await?;
        
        // 提交变更
        let commit_message = format!(
            "更新配置: {}:{}:{}",
            environment.application,
            environment.profile,
            environment.label
        );
        
        let commit_id = self.commit_changes(&commit_message, user).await?;
        
        // 推送到远程（如果配置了远程仓库）
        if let Err(e) = self.push_updates(&commit_message).await {
            tracing::warn!("⚠️ 推送Git更新失败: {}", e);
        }
        
        Ok(commit_id)
    }
    
    async fn delete(
        &self,
        environment: &ConfigEnvironment,
        user: &str,
    ) -> ConfigurationResult<()> {
        // 确保仓库已初始化
        if self.repository.lock().await.is_none() {
            self.initialize().await?;
        }
        
        let config_path = self.get_config_file_path(environment);
        
        if !config_path.exists() {
            return Err(Box::new(ConfigurationServerError::ConfigNotFound {
                application: environment.application.clone(),
                profile: environment.profile.clone(),
                label: environment.label.clone(),
            }) as Box<dyn std::error::Error + Send + Sync>);
        }
        
        // 删除配置文件
        fs::remove_file(&config_path).await?;
        
        // 提交变更
        let commit_message = format!(
            "删除配置: {}:{}:{}",
            environment.application,
            environment.profile,
            environment.label
        );
        
        self.commit_changes(&commit_message, user).await?;
        
        // 推送到远程
        if let Err(e) = self.push_updates(&commit_message).await {
            tracing::warn!("⚠️ 推送Git更新失败: {}", e);
        }
        
        Ok(())
    }
    
    async fn get_config_history(
        &self,
        environment: &ConfigEnvironment,
    ) -> Result<Vec<ConfigChangeRecord>> {
        // 确保仓库已初始化
        if self.repository.lock().await.is_none() {
            self.initialize().await?;
        }
        
        let config_path = self.get_config_file_path(environment);
        let relative_path = config_path.strip_prefix(&self.repo_path)
            .map_err(|_| ConfigurationServerError::StorageError("无效的配置文件路径".to_string()))?;
        
        let mut history = Vec::new();
        
        let repo_guard = self.repository.lock().await;
        if let Some(repo) = repo_guard.as_ref() {
            let mut revwalk = repo.revwalk()
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            revwalk.push_head()
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            for commit_oid in revwalk {
                let commit_oid = commit_oid
                    .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
                
                let commit = repo.find_commit(commit_oid)
                    .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
                
                // 检查此提交是否涉及目标文件
                let tree = commit.tree()
                    .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
                
                if tree.get_path(relative_path).is_ok() {
                    let record = ConfigChangeRecord {
                        id: commit.id().to_string(),
                        application: environment.application.clone(),
                        profile: environment.profile.clone(),
                        label: environment.label.clone(),
                        operation: "UPDATE".to_string(),
                        user: commit.author().name().unwrap_or("unknown").to_string(),
                        timestamp: SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(
                            commit.time().seconds() as u64
                        ),
                        description: commit.message().unwrap_or("").to_string(),
                        changes: HashMap::new(),
                    };
                    
                    history.push(record);
                }
            }
        }
        
        Ok(history)
    }
    
    async fn rollback_config(
        &self,
        environment: &ConfigEnvironment,
        version: &str,
        user: &str,
    ) -> Result<()> {
        // 确保仓库已初始化
        if self.repository.lock().await.is_none() {
            self.initialize().await?;
        }
        
        let repo_guard = self.repository.lock().await;
        if let Some(repo) = repo_guard.as_ref() {
            // 查找目标提交
            let target_oid = Oid::from_str(version)
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            let target_commit = repo.find_commit(target_oid)
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            // 获取目标提交的树
            let target_tree = target_commit.tree()
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            // 检出目标版本的文件
            let config_path = self.get_config_file_path(environment);
            let relative_path = config_path.strip_prefix(&self.repo_path)
                .map_err(|_| ConfigurationServerError::StorageError("无效的配置文件路径".to_string()))?;
            
            if let Ok(entry) = target_tree.get_path(relative_path) {
                let blob = repo.find_blob(entry.id())
                    .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
                
                fs::write(&config_path, blob.content()).await?;
                
                // 提交回滚
                let commit_message = format!(
                    "回滚配置 {}:{}:{} 到版本 {}",
                    environment.application,
                    environment.profile,
                    environment.label,
                    version
                );
                
                drop(repo_guard);
                self.commit_changes(&commit_message, user).await?;
                
                // 推送到远程
                if let Err(e) = self.push_updates(&commit_message).await {
                    tracing::warn!("⚠️ 推送Git更新失败: {}", e);
                }
                
                tracing::info!("🔄 配置已回滚到版本: {}", version);
            } else {
                return Err(ConfigurationServerError::ConfigNotFound {
                    application: environment.application.clone(),
                    profile: environment.profile.clone(),
                    label: environment.label.clone(),
                });
            }
        }
        
        Ok(())
    }
    
    async fn config_exists(&self, environment: &ConfigEnvironment) -> Result<bool> {
        let config_path = self.get_config_file_path(environment);
        Ok(config_path.exists())
    }
    
    async fn list_applications(&self) -> Result<Vec<String>> {
        // 确保仓库已初始化
        if self.repository.lock().await.is_none() {
            self.initialize().await?;
        }
        
        let mut applications = std::collections::HashSet::new();
        
        let mut entries = fs::read_dir(&self.repo_path).await?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if path.is_file() {
                if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
                    if filename.ends_with(&format!(".{}", self.config_extension)) {
                        let name_without_ext = filename.trim_end_matches(&format!(".{}", self.config_extension));
                        
                        // 解析应用名称
                        if let Some(app_name) = name_without_ext.split('-').next() {
                            applications.insert(app_name.to_string());
                        }
                    }
                }
            }
        }
        
        Ok(applications.into_iter().collect())
    }
    
    async fn list_profiles(&self, application: &str) -> Result<Vec<String>> {
        // 确保仓库已初始化
        if self.repository.lock().await.is_none() {
            self.initialize().await?;
        }
        
        let mut profiles = std::collections::HashSet::new();
        profiles.insert("default".to_string());
        
        let pattern = format!("{}-", application);
        
        let mut entries = fs::read_dir(&self.repo_path).await?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if path.is_file() {
                if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
                    if filename.starts_with(&pattern) && filename.ends_with(&format!(".{}", self.config_extension)) {
                        let name_without_ext = filename.trim_end_matches(&format!(".{}", self.config_extension));
                        
                        if let Some(profile) = name_without_ext.strip_prefix(&pattern) {
                            profiles.insert(profile.to_string());
                        }
                    }
                }
            }
        }
        
        Ok(profiles.into_iter().collect())
    }
    
    async fn list_labels(&self, _application: &str, _profile: &str) -> Result<Vec<String>> {
        // 获取Git标签和分支
        let repo_guard = self.repository.lock().await;
        if let Some(repo) = repo_guard.as_ref() {
            let mut labels = Vec::new();
            
            // 添加分支
            let branches = repo.branches(Some(git2::BranchType::Local))
                .map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            for branch in branches {
                let (branch, _) = branch.map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
                if let Some(name) = branch.name().map_err(|e| ConfigurationServerError::GitError(e.to_string()))? {
                    labels.push(name.to_string());
                }
            }
            
            // 添加标签
            repo.tag_foreach(|oid, name| {
                if let Ok(name_str) = std::str::from_utf8(name) {
                    if let Some(tag_name) = name_str.strip_prefix("refs/tags/") {
                        labels.push(tag_name.to_string());
                    }
                }
                true
            }).map_err(|e| ConfigurationServerError::GitError(e.to_string()))?;
            
            Ok(labels)
        } else {
            Ok(vec![self.default_branch.clone()])
        }
    }
}

#[async_trait]
impl ConfigStorage for GitStorage {
    async fn get_config(&self, environment: &ConfigEnvironment) -> ServerResult<ConfigResponse> {
        // 使用现有的ConfigurationStorage实现
        let data = self.load(environment).await
            .map_err(|e| ConfigurationServerError::StorageError(e.to_string()))?;
        
        // 转换为ConfigResponse格式
        let property_source = PropertySource {
            name: format!("{}:{}:{}", environment.application, environment.profile, environment.label),
            source: {
                let mut source = HashMap::new();
                // 将RustCloudConfig转换为HashMap<String, serde_json::Value>
                if let Ok(value) = serde_json::to_value(&data.config) {
                    if let serde_json::Value::Object(map) = value {
                        source = map;
                    }
                }
                source
            },
        };
        
        Ok(ConfigResponse {
            property_sources: vec![property_source],
            version: data.version,
            state: "success".to_string(),
            label: environment.label.clone(),
        })
    }
    
    async fn save_config(&self, environment: &ConfigEnvironment, config: &RustCloudConfig, user: &str) -> ServerResult<String> {
        self.save(environment, config, user).await
            .map_err(|e| ConfigurationServerError::StorageError(e.to_string()))
    }
    
    async fn delete_config(&self, environment: &ConfigEnvironment, user: &str) -> ServerResult<()> {
        self.delete(environment, user).await
            .map_err(|e| ConfigurationServerError::StorageError(e.to_string()))
    }
}